<template xmlns:v-model="http://www.w3.org/1999/xhtml">
  <div class="notebook-detail">
    <note-sidebar></note-sidebar>
    <div class="choose-note" v-if="!currentNote.id">
      选择左侧笔记
    </div>
    <div v-else class="note-detail">
      <div class="note-header">
        <div class="search-related">
          <!--<Input placeholder="搜索笔记..." style="width: 100%"></Input>-->
        </div>
        <div class="operation">
          <Button @click="doUpdateNote(currentNote)" type="primary" size="small">
            <Icon type="play"></Icon>
            保存
          </Button>
          <Button :disabled="!isRichText" @click="changeEditMarkdown" type="success" size="small">
            <span v-if="!isEdit">
              <Icon type="paper-airplane"></Icon>
              转Markdown
            </span>
            <span v-else>
              <Icon type="edit"></Icon>
              使用Markdown编辑
            </span>
          </Button>
          <Button @click="doDeleteNote" type="error" size="small">
            <Icon type="trash-b"></Icon>
            删除
          </Button>
        </div>
      </div>
      <div class="note-content">
        <div class="date-related">
          <Alert banner class="date-banner" type="success">
            <span class="create-time">创建时间: {{ _formateDate(currentNote.createdTime) }} ({{ _fullDate(currentNote.createdTime) }})</span>
            <span class="update-time">更新时间: {{ _formateDate(currentNote.modifiedTime) }} ({{ _fullDate(currentNote.modifiedTime) }})</span>
            <span class="note-status">状态: {{ statusText }}</span>
          </Alert>
        </div>
        <div class="note-title">
          <input :disabled="isEdit" type="text" v-model:value="currentNote.title" class="title-input"
                 placeholder="输入笔记标题">
          <Select v-model="selectTags" filterable multiple allow-create placeholder="设置标签">
            <Option v-for="item in noteTagList" v-bind:value="item.id" :key="item.id">{{ item.name }}</Option>
          </Select>
        </div>
        <div class="note-editor">
          <!-- <textarea v-if="!isEdit" class="editor-content" placeholder="输入笔记内容" v-model:value="currentNote.content"></textarea>
          <div class="note-content" v-html="editText2Html" v-else></div> -->
          <i-editor class="ii-editor" v-model="currentNote.content"></i-editor>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
  import NoteSidebar from '../../components/NoteSidebar.vue'
  import NoteEditor from './NoteEditor.vue'
  import {friendlyDate} from '../../common/js/date.js'
  import {mapState} from 'vuex'
  import MarkdownIt from 'markdown-it'
  import {getPrincipalInStore} from "../../common/js/auth";

  let md = new MarkdownIt();

  export default {
    name: 'NotebookDetail',
    components: {
      NoteSidebar,
      NoteEditor
    },
    created() {
      this.$Loading.start();
      let principal = getPrincipalInStore();
      if (!principal) {
        this.$Message.error('没有权限-请先登录');
        this.$router.push('/login');
      } else {
        this.$store.commit('changeIsLogin', true);
        this.$store.commit('setUser', principal);
        this.$store.commit('setUsername', principal.username);
        this.$Loading.finish();
      }
      // 如果请求路径上携带了noteId, 请求
      this.$store.commit('setCurrentNote', {});
      this.$store.commit('setSelectTags', []);
      // 查询标签
      this._getTagList();
    },
    data() {
      return {
        isEdit: true,
        statusText: '已完成',
        isRichText: true,
        editorContent: '',
        content: '',

        noteTagList: [
        ],
      }
    },
    computed: {
      ...mapState([
        'currentNote',
        'allNotes'
      ]),

      selectTags: {
        get: function () {
          return this.$store.state.selectTags;
        },
        set: function (val) {
          this.$store.commit('setSelectTags', val)
        }
      },

      editText2Html() {
        if (this.isEdit) {
          return md.render(this.currentNote.content)
        } else if (this.isRichText) {
          return this.$store.state.richText;
        }
      }
    },
    methods: {
      _formateDate(dateStr) {
        return friendlyDate(dateStr)
      },
      _fullDate(dateStr) {
        return dateStr;
      },
      changeEditMarkdown() {
        this.isEdit = !this.isEdit;
        if (!this.isEdit) {
          this.statusText = '编辑中'
        } else {
          this.statusText = '已完成'
        }
      },
      changeEditRich() {
        this.isRichText = !this.isRichText;
        if (!this.isRichText) {
          this.statusText = '编辑中'
        } else {
          this.statusText = '已完成'
        }
      },
      // 更新笔记内容
      doUpdateNote(note) {
        note.tags = [];
        if (this.selectTags && this.selectTags.length > 0) {
          this.selectTags.forEach(tagId => {
            note.tags.push(this.noteTagList.find(tag => tag.id === tagId));
          });
        }
        this.putRequest(this.$urlApi.UPDATE_NOTE, note).then(res => {
          console.log(res);
          this.statusText = '已保存';
        }).catch(err => {
          console.log(err);
        });
      },

      doDeleteNote() {
        let param = {'id': this.$route.query.noteId};
        this.postJSON(this.$urlApi.DISABLE_NOTE, param).then(res => {
          let tempNotes = [...this.allNotes];
          let iIndex = -1;
          tempNotes.forEach((item, index) => {
            if (item.id === this.$route.query.noteId) {
              iIndex = index
            }
          });
          tempNotes.splice(iIndex, 1);
          this.$store.commit('setAllNotes', tempNotes);
          this.$router.push(`/note?notebookId=${this.$route.query.notebookId}`)
        }).catch(err => {
          console.log(err);
        })
      },

      _getTagList() {
        this.postJSON(this.$urlApi.QUERY_TAG_LIST).then(res => {
          this.noteTagList = res.data;
        }).catch(err => {
          console.log(err);
        });
      },
    },
  }
</script>

<style lang="stylus" scoped>
  @import '../../common/stylus/variables.styl';

  .notebook-detail >>> .ivu-input
    height 400px

  .notebook-detail
    width 100%
    height 100%
    display flex
    align-items stretch
    overflow hidden

    .choose-note
      font-size 40px
      text-align center
      padding 20px

    .note-detail
      flex 1
      height 100%

      .note-header
        display flex
        justify-content space-between
        align-items center
        padding 10px 20px
        border-bottom 1px solid $line-color
        font-size 14px

        .search-related
          width 40%

      .note-content
        height 100%

        .date-related
          .update-time
            margin-left 10px

          .note-status
            margin-left 10px

        .note-title
          .title-input
            width 100%
            padding 10px 20px
            font-size 18px
            font-weight 700
            outline none
            border none

        .note-editor
          height 100%

          .editor-content
            width 100%
            height 75%
            padding 20px
            font-size 14px
            color #333
            border 1px dotted $theme-color
            outline none
            line-height 20px
            resize none

          .note-content
            padding 20px
            line-height 20px
</style>
